import { dataSource } from '../config/database';
import { ProductEntity } from '../entity/Product.entity';
import result from '../vo/result';
import { ResultCode } from '../enums/resultCode';
import { getIdByToken } from '../jwt/jwtService';
import ProductSkuEntity from '../entity/productSku.entity';

const tableRepository = dataSource.getRepository(ProductEntity);
const skuRepository = dataSource.getRepository(ProductSkuEntity);

export const addProductService = async (product: ProductEntity, token: string) => {
  product.imageList = JSON.stringify(product.imageList);
  product.productChoice = JSON.stringify(product.productChoice);
  product.adminId = getIdByToken(token);
  await tableRepository.save(product);
  //添加成功之后，返回productId
  return result.success({ productId: product.productId }, ResultCode.SUCCESS);
};

export const getProductListService = async (token: string, query) => {
  const { pageNo = 1, pageSize = 10, ...where } = query;
  const adminId = getIdByToken(token);
  //根据最新创建时间排序
  const list = (await tableRepository.find({
    where: {
      ...where,
      adminId
    },
    skip: (pageNo - 1 <= 0 ? 0 : pageNo - 1) * pageSize,
    take: pageSize,
    order:{
      createdTime: 'DESC'
    }
  }));
  list.map(item => {
    item.imageList = JSON.parse(item.imageList);
    item.productChoice = JSON.parse(item.productChoice);
    return item;
  });
  const totalCount = await tableRepository.count({
    where: {
      ...where,
      adminId
    }
  });
  return result.success({ list: list, totalCount: totalCount });
};

export const addProductSkuService = async (productId, skuList) => {
  if (skuList.length > 10) {
    return result.fail(ResultCode.FAIL, '商品规格数量不能超过10个');
  }
  skuList.map(async item => {
    item.specs = JSON.stringify(item.specs);
    item.productId = productId;
    try {
      await skuRepository.save(item);
    } catch (e) {
      return result.fail(ResultCode.FAIL, '失败');
    }
  });
  return result.success({}, '添加成功');
};

export const getProductSkuById = async (productId: number) => {
  const list = await skuRepository.find({ where: { productId } });
  list.map(item => {
    item.specs = JSON.parse(item.specs);
    return item;
  });
  return result.success({ list });
}

export const getPriceBySpecs = async (productId: number, selectedSpecs: { name: string, value: string }[]) => {
  const skus = await skuRepository.find({ where: { productId } });
  for (const sku of skus) {
    const specs = JSON.parse(sku.specs);
    const match = selectedSpecs.every(spec =>
      specs.some(s => s.name === spec.name && s.value === spec.value)
    );
    if (match) {
      return result.success({ price: sku.price }, '成功');
    }
  }
  return result.fail(ResultCode.FAIL, '该商品规格不存在');
};